import os
import shutil
import subprocess
import sys

baseDir = "/home/ttx/app/toolbox/MAT/"
matDownurl = "wget -P %s https://archive.eclipse.org/mat/1.11.0/rcp/%s"
zipName = "MemoryAnalyzer-1.11.0.20201202-linux.gtk.x86_64.zip"


def create_dir(dir_path):
    if os.path.exists(dir_path):
        return
    shutil.rmtree(dir_path)
    os.makedirs(dir_path)

def execCmd(cmd):
    try:
        return subprocess.call(cmd, shell=True)
    except BaseException as e:
        print(e)
        return 1

def setEnv():
    JAVA_HOME = '/home/ttx/app/jre'
    PATH = "%s/bin:%s" % (JAVA_HOME, os.environ['PATH'])
    CLASSPATH = ".:%s/lib/dt.jar:%s/lib/tools.jar" % (JAVA_HOME, JAVA_HOME)
    os.environ['JAVA_HOME'] = JAVA_HOME
    os.environ['PATH'] = PATH
    os.environ['CLASSPATH'] = CLASSPATH

def execue():
    if(not os.path.exists("%s%s"%(baseDir,zipName))):
        cmd = matDownurl % (baseDir,zipName)
        execCmd(cmd)
    if(not os.path.exists("%s/mat"%baseDir)):
        execCmd("unzip -d %s %s%s"%(baseDir,baseDir,zipName))
    if len(sys.argv)<2 or not sys.argv[1]:
        print("未指定hprof文件路径")
        usage()
        sys.exit()
    setEnv()
    cmd = "%s/mat/ParseHeapDump.sh %s  org.eclipse.mat.api:suspects org.eclipse.mat.api:overview org.eclipse.mat.api:top_components" %(baseDir,sys.argv[1])
    execCmd(cmd)

def usage():
    print("用法：python3 %s <hrop文件路径>" % os.path.basename(__file__))
    print("第一次执行会自动下载MAT并解压")
execue()